﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace new_problem
{
    internal class Landweber
    {
        public static Double[,] CalcLandweber(double[,] g, double[] x, double[] y, DataBuffer current)
        {
            double eps = 0.01;
            double alpha = 5.0;
            Double[,] z0 = DataGen.StartApproximation(); //начальное приближение
            Double[,] A = DataGen.GetFieldGrid(x, y, z0);
            Double[,] dA = MiscUtils.TransposeMatrix(DataGen.GetFieldDerivative(x, y, z0)); 
            Double[,] zk = new double[DataGen.N + 1, DataGen.N + 1]; // for result

            double nrm = MiscUtils.Norm(g);
            double err = 1.1;
            int k = 0;
            while (err > eps && k < 10000)
            {
                Double[,] S = MiscUtils.CalcS(A, dA, g);
                double stabFunc = DataGen.StabilisingFunctional(z0);
                for (int i = 0; i <= DataGen.N; i++)
                    for (int j = 0; j <= DataGen.N; j++)
                        zk[i, j] = z0[i, j] - alpha*S[i, j];// *stabFunc;

                z0 = zk;
                A = DataGen.GetFieldGrid(x, y, z0);
                dA = DataGen.GetFieldDerivative(x, y, z0);
                err = MiscUtils.Norm(MiscUtils.SubstractMatrix(A, g)) / nrm;

                //alpha = 0.8;

                Console.WriteLine("L: " + k + ": " + err);// + ", alpha: " + alpha);
                k++;
            }
            current.L = k;
            current.LErr = err;
            return zk;
        }
    }
}
